package com.yuezhu.versionup;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.yuezhu.been.UserMsg;
import com.yuezhu.com_volley.OkRequestQueue;
import com.yuezhu.com_volley.OkVolley;
import com.yuezhu.constante.Intents;
import com.yuezhu.sweetdialog.SweetAlertDialog;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.StringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class VersionCheckUtil {
    private static final String FLAG = "=";
    private static final String KEY_REQUEST = "689d3783957d65d57229ba3dc70a20fb";
    /**
     * 单例对象实例
     */
    private static VersionCheckUtil instance = null;
    private Context context;
    protected OkRequestQueue queue;
    private View backView;
    private VersionCheckResult versionCheckResult;

    public static VersionCheckUtil getInstance(Context context, View backView) {
        if (instance == null) {
            instance = new VersionCheckUtil(context, backView);
        }
        return instance;
    }

    public void setBackView(View backView) {
        this.backView = backView;
    }

    public VersionCheckUtil setBackViewInstance(View backView) {
        this.backView = backView;
        return instance;
    }

    private VersionCheckUtil(Context context, View backView) {
        this.context = context;
        queue = OkVolley.newOkRequestQueue(this.context);
        this.backView = backView;
    }

    /**
     * 监测新版本
     *//*
    public void checkVersion(VersionCheckResult versionCheckResult) {
		this.versionCheckResult = versionCheckResult;
		if (NetworkUtils.isNetworkAvailable(context)) {
			TaskEngine.getInstance().startVersionTask(queue,
					getOsVersion(context), versionponseLis, Errorlis);
		} else {
			MyToast.showDefaltToast("网络异常");
		}
	}*/

    /**
     * 返回当前系统版本名
     */
    public String getOsVersion(Context context) {
        return Build.VERSION.RELEASE;
    }

    public String appendUrl(Map<String, String> map) {
        String url = "";
        return url;
    }

    /**
     * 获取设备id
     *
     * @return
     */
    public String getDevID() {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String id = tm.getDeviceId();
        return id;
    }

    //获取设备类型
    public String getPhoneType() {
        Build bd = new Build();
        String model = bd.MODEL;
        return model.replace(" ", "_");
    }

    public String contentUrl() {
        String url = "&devId=" + getDevID() + "&devModel=" + getPhoneType() + "&devOs=android" + "&osVersion=" + getOsVersion(context);
        return url;
    }

    public String getBaseParams(Map<String, String> map1, String... strs) {
        Map<String, String> map = map1;
        List<String> list = new ArrayList<String>();
        list.add("devId=" + getDevID());
        list.add("devModel=" + getPhoneType());
        list.add("devOs=android");
        list.add("osVersion=" + getOsVersion(context));
        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + map.get(key));
            list.add(getTokenParams(key, map.get(key)));
        }


        map.put("devId", getDevID());
        map.put("devModel", getPhoneType());
        map.put("devOs", "android");
        map.put("osVersion", getOsVersion(context));

        for (String str : strs) {
            list.add(str);
        }
        strs = null;
        strs = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strs[i] = list.get(i);
        }
        String checkToken = getCheckToken(strs);
        map.put("checkToken", checkToken);
        checkToken = pink(map);
        return checkToken;
    }

    public String getSendMailBaseParams(Map<String, String> map1) {
        Map<String, String> map = map1;
        List<String> list = new ArrayList<String>();

        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + map.get(key));
            list.add(getTokenParams(key, map.get(key)));
        }
        String[] strs = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strs[i] = list.get(i);
        }
        String checkToken = getCheckToken(strs);
        map.put("checkToken", checkToken);
        if (map.get("authToken") != null) {
            map.put("authToken", map.get("authToken"));
        }
        checkToken = pink(map);
        return checkToken;
    }

    public String getBase1Params(Map<String, String> map1, String... strs) {
        Map<String, String> map = map1;
        List<String> list = new ArrayList<String>();

        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + map.get(key));
            list.add(getTokenParams(key, map.get(key)));
        }


        for (String str : strs) {
            list.add(str);
        }
        strs = null;
        strs = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            strs[i] = list.get(i);
        }
        String checkToken = getCheckToken(strs);
        map.put("checkToken", checkToken);
        map.put("authToken", UserMsg.getInstance().getAuthToken());
        checkToken = pink(map);
        return checkToken;
    }

    public String getTokenParams(String name, String value) {
        return name + FLAG + value;
    }

    public String getTokenParamsEncode(String name, String value) {
        return name + FLAG + StringUtil.Escape(value);
    }

    private String pink(Map<String, String> map1) {
        String pink = "";
        boolean NOA = false;
        List<String> list = new ArrayList<String>();
        String[] array = null;

        array = new String[map1.size()];
        for (String key : map1.keySet()) {
            LogUtils.e("key= " + key + " and value= " + map1.get(key));
        /*if (NOA){
            pink = pink +"&"+getTokenParams(key,map1.get(key));
		}else {
			pink = pink +getTokenParams(key,map1.get(key));
		}
		NOA = true ;*/
            list.add(key);
        }
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i);
        }
        Arrays.sort(array);
        for (String s : array) {
            LogUtils.e("上传排序", s);
            if (NOA) {
                pink = pink + "&" + getTokenParamsEncode(s, map1.get(s));
            } else {
                pink = pink + getTokenParamsEncode(s, map1.get(s));
            }
            NOA = true;
        }
        return pink;
    }

    public static String getCheckToken(String... strs) {

        String[] array = null;

        array = new String[strs.length];

        for (int i = 0; i < strs.length; i++) {
            array[i] = strs[i];
        }

        Arrays.sort(array);
        String checkToken = "";
        for (String s : array) {
            LogUtils.e("加密排序", s);
            checkToken = checkToken + s.substring(s.indexOf(FLAG) + 1);
        }

        checkToken = checkToken + KEY_REQUEST;
        LogUtils.e("加密前", checkToken);
        checkToken = toMD5(checkToken);
        LogUtils.e("加密后", checkToken);
        return checkToken;
    }


    public static String toMD5(String plainText) {
        try {
            // 生成实现指定摘要算法的 MessageDigest 对象。
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节数组更新摘要。
            md.update(plainText.getBytes());
            // 通过执行诸如填充之类的最终操作完成哈希计算。
            byte b[] = md.digest();
            // 生成具体的md5密码到buf数组
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            return buf.toString();// 32 buf.toString().substring(8, 24)
            // 16（32位截取）
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    Response.ErrorListener Errorlis = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.e("errorurl", volleyError.toString());
        }
    };
    Response.Listener versionponseLis = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject json) {
            LogUtils.e("url", json.toString());
            try {
                String status = json.getString("status");
                String url = json.getString("url");
                if (status.equals("1")) {
                    showVersionFleshDialog(url);
                } else {
                    if (versionCheckResult != null) {
                        versionCheckResult.verCheckRes();
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    };

    // 版本更新dialog 提示
    private void showVersionFleshDialog(final String url) {
        new SweetAlertDialog(context, SweetAlertDialog.INIT_CANCLE)
                .setBackView(backView)
                .setTitleText("")
                .setContentText("发现新版本需要更新吗？")
                .setCancelText("取消")
                .setConfirmText("确认")
                .showCancelButton(true)
                .setCancelClickListener(
                        new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog,
                                                int cancle) {
                                sDialog.dismiss();
                            }
                        })
                .setConfirmClickListener(
                        new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog,
                                                int cancle) {
                                sDialog.dismiss();
                                Intent startIntent = new Intent(context,
                                        DownService.class);
                                startIntent.putExtra(Intents.VERSION, url);
                                context.startService(startIntent);
                            }
                        }).show();
    }

    // 最新版本时调用外部提示
    public interface VersionCheckResult {
        void verCheckRes();
    }
}
